package com.ease.concurrent.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.IntStream;

/**
 * @author: chenhs
 * @date: Created in 7:40 2020/3/15
 **/
public class CollectionTest {

    public static void main(String[] args) {
        // 线程安全java.util.ConcurrentModificationException
        //List<String> data = new ArrayList<>();

        //1. 使用Vector
        //List<String> data = new Vector<>();

        //2. 使用Collections工具类的synchronizedList方法
        //List<String> data = Collections.synchronizedList(new ArrayList<>());

        //3. 使用CopyOnWriteArrayList(重入锁来解决线程安全问题)
        List data = new CopyOnWriteArrayList();

        IntStream.range(0, 30).forEach(
                i -> new Thread(() -> data.add(String.valueOf(i)), String.valueOf(i)).start()
        );
        System.out.println(data);
    }
}


